// 简化的进程服务实现

use std::collections::HashMap;
use log::info;
use super::{BaseService, ServiceError, ServiceStatus};

// 进程状态
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessState {
    Created,
    Ready,
    Running,
    Blocked,
    Terminated,
}

// 进程信息
#[derive(Debug, Clone)]
pub struct ProcessInfo {
    pub pid: u32,
    pub name: String,
    pub state: ProcessState,
    pub priority: u8,
    pub memory_usage: usize,
    pub cpu_time: u64,
}

// 简化的进程服务
pub struct ProcessService {
    processes: HashMap<u32, ProcessInfo>,
    next_pid: u32,
    status: ServiceStatus,
}

impl ProcessService {
    pub fn new() -> Result<Self, ServiceError> {
        info!("Creating new Process Service");
        
        Ok(ProcessService {
            processes: HashMap::new(),
            next_pid: 1, // PID 0 通常为内核进程
            status: ServiceStatus::Stopped,
        })
    }
    
    // 创建新进程
    pub fn create_process(&mut self, name: String, priority: u8) -> Result<u32, ServiceError> {
        if self.status != ServiceStatus::Running {
            return Err(ServiceError::ProcessError("Service not running".to_string()));
        }
        
        if priority > 31 {
            return Err(ServiceError::ProcessError("Priority must be between 0-31".to_string()));
        }
        
        let pid = self.next_pid;
        self.next_pid += 1;
        
        let process = ProcessInfo {
            pid,
            name: name.clone(),
            state: ProcessState::Created,
            priority,
            memory_usage: 0,
            cpu_time: 0,
        };
        
        self.processes.insert(pid, process);
        info!("Created process '{}' with PID {}", name, pid);
        
        Ok(pid)
    }
    
    // 启动进程
    pub fn start_process(&mut self, pid: u32) -> Result<(), ServiceError> {
        if let Some(process) = self.processes.get_mut(&pid) {
            if process.state == ProcessState::Created {
                process.state = ProcessState::Ready;
                info!("Process {} moved to ready state", pid);
                Ok(())
            } else {
                Err(ServiceError::ProcessError(format!("Process {} not in created state", pid)))
            }
        } else {
            Err(ServiceError::ProcessError(format!("Process {} not found", pid)))
        }
    }
    
    // 终止进程
    pub fn terminate_process(&mut self, pid: u32) -> Result<(), ServiceError> {
        if let Some(process) = self.processes.get_mut(&pid) {
            process.state = ProcessState::Terminated;
            info!("Terminated process {}", pid);
            Ok(())
        } else {
            Err(ServiceError::ProcessError(format!("Process {} not found", pid)))
        }
    }
    
    // 获取进程信息
    pub fn get_process_info(&self, pid: u32) -> Option<&ProcessInfo> {
        self.processes.get(&pid)
    }
    
    // 获取所有进程列表
    pub fn list_processes(&self) -> Vec<&ProcessInfo> {
        self.processes.values().collect()
    }
    
    // 更新进程状态
    pub fn update_process_state(&mut self, pid: u32, new_state: ProcessState) -> Result<(), ServiceError> {
        if let Some(process) = self.processes.get_mut(&pid) {
            let old_state = process.state;
            process.state = new_state;
            info!("Process {} state changed from {:?} to {:?}", pid, old_state, new_state);
            Ok(())
        } else {
            Err(ServiceError::ProcessError(format!("Process {} not found", pid)))
        }
    }
    
    // 更新进程CPU时间
    pub fn update_cpu_time(&mut self, pid: u32, additional_time: u64) -> Result<(), ServiceError> {
        if let Some(process) = self.processes.get_mut(&pid) {
            process.cpu_time += additional_time;
            Ok(())
        } else {
            Err(ServiceError::ProcessError(format!("Process {} not found", pid)))
        }
    }
    
    // 更新进程内存使用
    pub fn update_memory_usage(&mut self, pid: u32, memory_usage: usize) -> Result<(), ServiceError> {
        if let Some(process) = self.processes.get_mut(&pid) {
            process.memory_usage = memory_usage;
            Ok(())
        } else {
            Err(ServiceError::ProcessError(format!("Process {} not found", pid)))
        }
    }
    
    // 获取进程统计信息
    pub fn get_stats(&self) -> ProcessStats {
        let total_processes = self.processes.len();
        let running_processes = self.processes.values()
            .filter(|p| p.state == ProcessState::Running)
            .count();
        let total_memory: usize = self.processes.values()
            .map(|p| p.memory_usage)
            .sum();
        let total_cpu_time: u64 = self.processes.values()
            .map(|p| p.cpu_time)
            .sum();
            
        ProcessStats {
            total_processes,
            running_processes,
            total_memory,
            total_cpu_time,
        }
    }
}

impl BaseService for ProcessService {
    fn start(&mut self) -> Result<(), ServiceError> {
        if self.status == ServiceStatus::Running {
            return Ok(());
        }
        
        info!("Starting Process Service");
        
        // 创建初始系统进程
        self.create_process("init".to_string(), 0)?;
        
        self.status = ServiceStatus::Running;
        info!("Process Service started successfully");
        Ok(())
    }
    
    fn stop(&mut self) -> Result<(), ServiceError> {
        if self.status == ServiceStatus::Stopped {
            return Ok(());
        }
        
        info!("Stopping Process Service");
        
        // 终止所有进程
        for pid in self.processes.keys().copied().collect::<Vec<_>>() {
            let _ = self.terminate_process(pid);
        }
        
        self.status = ServiceStatus::Stopped;
        info!("Process Service stopped");
        Ok(())
    }
    
    fn status(&self) -> ServiceStatus {
        self.status
    }
}

// 进程统计信息
#[derive(Debug, Clone)]
pub struct ProcessStats {
    pub total_processes: usize,
    pub running_processes: usize,
    pub total_memory: usize,
    pub total_cpu_time: u64,
}

impl ProcessStats {
    pub fn average_memory_per_process(&self) -> f64 {
        if self.total_processes == 0 {
            return 0.0;
        }
        self.total_memory as f64 / self.total_processes as f64
    }
    
    pub fn cpu_utilization(&self) -> f64 {
        // 简化计算：假设每个进程运行时间占总时间的比例
        if self.total_processes == 0 {
            return 0.0;
        }
        (self.running_processes as f64 / self.total_processes as f64) * 100.0
    }
}